from django.shortcuts import render
from django.views import View
from django import http
from django.core.paginator import Paginator, EmptyPage
from django.utils import timezone

# Create your views here
#
from contents.utils import get_categories
from .models import GoodsCategory,SKU,GoodsVisitCount
from goods.utils import get_breadcrumb
from meiduo_mail.utils.response_code import RETCODE

# class ListView(View):
#     def get(self,request,category_id,page_num):
#
#
#     # 校验
#         try:
#             cat3 = GoodsCategory.objects.get(id=category_id)
#         except GoodsCategory.DoesNotExist:
#             return http.HttpResponseForbidden('category_id错误')
#     # 包装面包屑数据
#         cat1 = cat3.parent.parent
#         cat1.url = cat1.goodschannel_set.all()[0].url
#         breadcrumb = {
#             'cat1':cat1,
#             'cat2':cat3.parent,
#             'cat3':cat3
#         }
#         context = {
#             'categories':get_categories(),
#             'breadcrumb':breadcrumb
#         }
#         return render(request,'list.html',context)

class ListView(View):
    """商品列表界面"""

    def get(self, request, category_id, page_num):

        # 校验category_id是否真实有效
        try:
            cat3 = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.HttpResponseForbidden('category_id不存在')

        # 包装面包屑数据

        # cat1 = cat3.parent.parent
        # cat1.url = cat1.goodschannel_set.all()[0].url
        # breadcrumb = {
        #     'cat1': cat1,
        #     'cat2': cat3.parent,
        #     'cat3': cat3
        # }
        sort = request.GET.get('sort','default')
        if sort == 'price':
            sort_field = '-price'
        elif sort =='hot':
            sort_field = '-sales'
        else:
            sort = 'default'
            sort_field = '-create_time'
        # 查询出指定三级类型下的所有要展示的sku商品
        sku_qs = cat3.sku_set.filter(is_launched=True).order_by(sort_field)
        # total_count = sku_qs.count()
        # page = 5  # 每页显示5条
        # page_num = int(page_num)
        # total_page = total_count // page + ((total_count % page) and 1)
        # page_skus = sku_qs[(page_num - 1) * page: page_num * page]
        # 创建分页器 (要分页的所有数据, 每页显示多少条数据)
        paginator = Paginator(sku_qs, 5)
        total_page = paginator.num_pages  # 获取总页数
        try:
            page_skus = paginator.page(page_num)  # 获取指定页的数据
        except EmptyPage:
            return http.HttpResponseForbidden('没有指定页')


        context = {

            'categories': get_categories(),  # 商品分类数据
            'breadcrumb': get_breadcrumb(cat3),   # 面包屑导航数据
            'category': cat3,  # 三级类别
            'page_skus': page_skus,   # 指定页中所有sku商品数据
            'page_num': page_num,  # 当前显示第几页
            'total_page': total_page,  # 总页数
            'sort': sort,  # 当前是按照什么规则排序
        }
        return render(request, 'list.html', context)


class HotGoodsView(View):
    def get(self,request,category_id):
        # 校验
        try:
            cat3 = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.HttpResponseForbidden('category_id不存在')
        # 查询当前三级类型下的所有商品并以销量进行降徐排序
        sku_qs = cat3.sku_set.order_by('-sales')[:2]
        sku_list = []
        # 模型转字典
        for sku in sku_qs:
            sku_list.append({
                'id':sku.id,
                'name':sku.name,
                'price':sku.price,
                'default_image_url':sku.default_image.url
            })
            # 响应
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'OK','hot_skus':sku_list})



# class DetailView(View):
#     def get(self,request,sku_id):
#         try:
#             sku = SKU.objects.get(id=sku_id)
#         except SKU.DoesNotExist:
#             return render(request,'404.html')
#         # 查询当前sku的三级类别
#         category = sku.category
#         spu = sku.spu
#         # 准备当前商品的规格选项列表
#         current_sku_spec_qs = sku.specs.order_by('spec_id')
#         current_sku_option_ids = []
#         # 获取当前正显示的sku商品的规格选项id列表
#         for current_sku_spec in current_sku_spec_qs:
#             current_sku_option_ids.append(current_sku_spec.option_id)
#
#         # 构造规格选择仓库
#         temp_sku_qs = spu.sku_set.all()
#         # 选择仓库大字典
#         spec_sku_map = {}
#         for temp_sku in temp_sku_qs:
#         # 查询每一个sku的规格数据
#         #     temp_spec_qs = temp_sku.spec.order_by('spec_id')
#             temp_spec_qs = temp_sku.specs.order_by('spec_id')
#             temp_sku_option_ids = []
#             for temp_spec in temp_spec_qs:
#                 temp_sku_option_ids.append(temp_spec.option_id)
#             spec_sku_map[tuple(temp_sku_option_ids)]=temp_sku.id
#
#         # 组合，并找到skuid绑定
#         # 获取当前spu中的所有规格
#         # 遍历当前所有的规格
#         # 获取当前规格中的所有选项
#         # 复制一个新的当前显示商品的规格选项列表
#         # 遍历当前规格下的所有选项
#         # [8, 12]
#         # 给每个选项对象绑定下他sku_id属性
#         # 把规格下的所有选项绑定到规格对象的spec_options属性上
#         spu_spec_qs = spu.specs.order_by('id')
#         for index,spec in enumerate(spu_spec_qs):
#             spec_option_qs = spec.options.all()
#             temp_option_ids = current_sku_option_ids[:]
#             for option in spec_option_qs:
#                 temp_option_ids[index] = option.id
#                 option.sku_id = spec_sku_map.get(tuple(temp_option_ids))
#
#             spec.spec_options = spec_option_qs
#
#         context = {
#             'categories':get_categories(),
#             'breadcrumb':get_categories(),
#             'sku':sku,
#             'category':category,
#             'spu':spu,
#             'spec_id':spu_spec_qs
#         }
#
#
#         return render(request,'detail.html',context)


class DetailView(View):
    """商品详情界面"""

    def get(self, request, sku_id):
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        category = sku.category
        spu = sku.spu
        current_sku_spec_qs = sku.specs.order_by('spec_id')
        current_sku_option_ids = []  # [8, 11]
        for current_sku_spec in current_sku_spec_qs:
            current_sku_option_ids.append(current_sku_spec.option_id)
        temp_sku_qs = spu.sku_set.all()  # 获取当前spu下的所有sku

        spec_sku_map = {}
        for temp_sku in temp_sku_qs:
            temp_spec_qs = temp_sku.specs.order_by('spec_id')
            temp_sku_option_ids = []  # 用来包装每个sku的选项值
            for temp_spec in temp_spec_qs:
                temp_sku_option_ids.append(temp_spec.option_id)
            spec_sku_map[tuple(temp_sku_option_ids)] = temp_sku.id


        spu_spec_qs = spu.specs.order_by('id')

        for index, spec in enumerate(spu_spec_qs):
            spec_option_qs = spec.options.all()
            temp_option_ids = current_sku_option_ids[:]
            for option in spec_option_qs:
                temp_option_ids[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(temp_option_ids))

            spec.spec_options = spec_option_qs
        context = {
            'categories': get_categories(),
            'breadcrumb': get_breadcrumb(category),
            'sku': sku,
            'category': category,
            'spu': spu,
            'spec_qs': spu_spec_qs,
        }
        return render(request, 'detail.html', context)



class VisitCountView(View):
    def post(self,request,category_id):
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.HttpResponseForbidden('categories传输错误')

        # today_data = timezone.now()
        date = timezone.now()

        try:
            # visit_model = GoodsVisitCount.objects.get(data=today_data,category=category)
            visit_model = GoodsVisitCount.objects.get(category=category, date=date)


        except GoodsVisitCount.DoesNotExist:
            visit_model = GoodsVisitCount(
                category=category
            )

        visit_model.count += 1
        visit_model.save()
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'OK'})




